package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.example.mapper.VipMapper;
import org.example.pojo.Vip;
import org.example.service.VipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.lang.reflect.Field;
import java.util.List;

@Service
public class VipServiceImpl implements VipService {
    @Autowired
    VipMapper vipMapper;
    //查询全部会员
    @Override
    public List<Vip> findallVipList() {
        return vipMapper.selectList(null);
    }
    //根据id删除会员
    @Override
    public int deletevip(int id) {
       return vipMapper.deleteById(id);
    }
    //更新会员信息
    @Override
    @Transactional //开启事务
    public Vip updateVip(Vip vip) {
        //获取对象的所有字段
        Field[] fields = vip.getClass().getDeclaredFields();
        //构造更新操作
        UpdateWrapper<Vip> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",vip.getId());
        for (Field field : fields){
            //设置可访问私有字段
            field.setAccessible(true);
            try {
                //获取字段的值
                Object value = field.get(vip);
                if (value != null && !"".equals(value.toString())){
                    wrapper.set(field.getName(),value);
                }
            } catch (IllegalAccessException e) {
                TransactionAspectSupport.currentTransactionStatus();
                throw new RuntimeException("更新用户信息失败"+e);
            }
        }
        //执行更新操作
        int update = vipMapper.update(null,wrapper);
        //如果更新成功，则返回更新的对象，否则返回null
        if (update > 0){
            return vipMapper.selectById(vip.getId());
        }else {
            return null;
        }
    }
    //新增会员
    @Override
    public void addvip(Vip vip) {
        vipMapper.insert(vip);
    }
    //根据id查询会员信息
    @Override
    public Vip findByidvip(int id) {
        return vipMapper.selectById(id);
    }
}
